package com.solarStruggle.controls

import javax.swing.{ImageIcon}
import scala.swing.{Button, Component, ListView, ScrollPane}
import scala.swing.event.{ButtonClicked, ComponentEvent, SelectionChanged}
import domain.{Shard, ShardFactory}
import util.{ResourceLoader}

case class SelectedShardChanged(source0: Component, selectedShards: Seq[Shard]) extends ComponentEvent {
	override val source = source0
}

/**
 * Used to select shard(s)
 */
class ShardSelector[Type <: Shard](availableShardFactories: Seq[ShardFactory], info: InfoDisplay[Type])
extends MigPanel {

	/**
	 * The maximum number of shards that can be selected from this screen
	 */
	private var maxShards0: Int = 1

	def maxShards = maxShards0
	def maxShards_=(value: Int) { maxShards0 = value; disableButtons() }

	protected def disableButtons() {
		addButton.enabled = selectedList.listData.length < maxShards
		removeButton.enabled = selectedList.listData.length > 0
	}

	val shardList = new ListView[ShardFactory] {
		listData = availableShardFactories
		renderer = new SvgIconListRenderer[ShardFactory]( { a => a.singleton.name }, { a => println(a.singleton.svgFile); a.singleton.svgFile })
		selection.reactions += {
			case SelectionChanged(_) =>
				info.data = Some(selection.items.first.singleton.asInstanceOf[Type])
				disableButtons()
		}
	}

	val selectedList = new ListView[Shard] {
		renderer = new SvgIconListRenderer[Shard]( { a => a.name }, { a => a.svgFile })
	}

	val addButton = new Button {
		icon = new ImageIcon(ResourceLoader.getResourceBytes("img/green-go-next.png"))
		reactions += {
			case ButtonClicked(_) =>
				if(selectedList.listData.length >= maxShards) {
					selectedList.listData = selectedList.listData.drop(1)
				}
				if(selectedList.listData.length < maxShards) {
					selectedList.listData ++= List(shardList.selection.items.first())
				}
				ShardSelector.this.publish(new SelectedShardChanged(ShardSelector.this, selectedList.listData))
				disableButtons()
		}
	}

	val removeButton = new Button {
		icon = new ImageIcon(ResourceLoader.getResourceBytes("img/green-go-previous.png"))
		reactions += {
			case ButtonClicked(_) =>
				selectedList.listData = selectedList.listData.filter { c => !selectedList.selection.items.contains(c) }
				ShardSelector.this.publish(new SelectedShardChanged(ShardSelector.this, selectedList.listData))
		}
	}

	add(new ScrollPane(shardList), "width 250, height 400, spany 3, growy")
	add(info, "spanx 2, height 200, wrap")
	add(addButton)
	add(new ScrollPane(selectedList), "spany 2, wrap, growx, growy")
	add(removeButton)

	disableButtons()
}
